const express = require("express");
const app = express();

// 引入mysql,查询数据库
const mysql = require("mysql");
const conn = mysql.createConnection({
    host: "127.0.0.1",
    database: "mysql_001",
    user: "root",
    password: "root"
})



// 中间件
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }))


// 静态文件托管
app.set("view engine", "ejs");

app.set("views", "view");


app.use("/node_modules", express.static("./node_modules"));


// 首页渲染
app.get("/", (req, res) => {
    res.render("./index.ejs", {})
})

// 登录页渲染
app.get("/login", (req, res) => {
    res.render("./wide/login.ejs");
})

// 注册页验证
app.post("/register", (req, res) => {
    const body = req.body;
    if (body.username.trim().length <= 0 || body.password.trim().length <= 0 || body.nickname.trim().length <= 0) {
        res.send({
            msg: "请输入完整信息",
            status: 501
        })
    };

    const mysql1 = "select count(*) as count from blog_users where username=?"
    conn.query(mysql1, body.username, (err, result) => {
        if (err) return res.send({
            msg: "查重失败",
            status: 500
        });
        if (result[0].count != 0)
            return res.send({
                msg: "用户名重复",
                status: 501
            });
        const mysq2 = "insert into blog_users set ?";
        conn.query(mysq2, body, (err, result) => {
            if (err) return res.send({ msg: "用户添加失败", status: 503 });

        })

    })
    res.send({
        msg: "注册用户成功",
        status: "200"
    })
})

app.get("/register", (req, res) => {
    res.render("./wide/register.ejs");
})


app.listen(3000, () => {
    console.log("http://localhost:3000");
})